package com.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.model.auto.SchoolSort;
import com.service.ISchoolSortService;
import com.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author zhaoyifan
 * @date 2024/9/17 17:45
 */
@RestController
@RequestMapping("/schoolSort")
public class SchoolSortController {

    @Autowired
    ISchoolSortService schoolSortService;

    @GetMapping("/list")
    public R list(Integer year, String name, Integer pageNum,Integer pageSize) {
        if(Objects.isNull(pageNum)){
            pageNum = 1;
        }
        if(Objects.isNull(pageSize)){
            pageSize = 20;
        }
        PageInfo<SchoolSort> resultInfo = PageHelper.startPage(pageNum, pageSize)
                .doSelectPageInfo(() -> {
                    List<SchoolSort> list = schoolSortService.list(new LambdaQueryWrapper<SchoolSort>()
                            .eq(Objects.nonNull(year), SchoolSort::getYear, year)
                            .like(StringUtils.hasText(name), SchoolSort::getName, name)
                    );
                });

        return R.ok(resultInfo.getList()).put("total", resultInfo.getTotal());
    }

    @GetMapping("/years")
    public R list() {
        List<SchoolSort> list = schoolSortService.list(new LambdaQueryWrapper<SchoolSort>()
                .select(SchoolSort::getYear)
                .groupBy(SchoolSort::getYear)
                .orderByDesc(SchoolSort::getYear));

        List<Integer> years = new ArrayList<>();
        for(SchoolSort schoolSort:list){
            years.add(schoolSort.getYear());
        }
        return R.ok(years);
    }
}
